require "Common/define"
require "Logic/Config"
require "Common/functions"

RedDotsMailHandler ={};
local this = RedDotsMailHandler;

function RedDotsMailHandler.init()
    CloseEvent(Config.EventType.Fresh_Email,this.update);
    ListenEvent(Config.EventType.Fresh_Email,this.update);

    return this;
end

--参数1：邮件id，nil代表全部检查
function RedDotsMailHandler.getFlag(...)
    local flag = Config.RedDotsFlagState.None;
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.Mail,false) then
        local mailId = ...;
        if mailId~=nil then
            local list = logicMgr.EmailManager.getEmailList();
            for key, value in pairs(list) do
                if value.mailId == mailId then
                    flag = this.getFlagByMail(value);
                    break;
                end
            end
        else
            local list = logicMgr.EmailManager.getEmailList();
            for key, value in pairs(list) do
                flag = this.getFlagByMail(value);
                if flag == Config.RedDotsFlagState.Needful then
                    break;
                end
            end
        end
    end
    return flag;
end

function RedDotsMailHandler.getFlagByMail(mail)

    --printTable(mail);

    local flag = Config.RedDotsFlagState.None;

    if mail.mailRead ~=1 then
        flag = Config.RedDotsFlagState.Needful;
    elseif mail.mailGetItems~=1 and #mail.rewards>0 then
        flag = Config.RedDotsFlagState.Needful;
    end

    if  mail.deadTime > 0 and HelperFunc.GetServerTime() >= mail.deadTime then
        flag = Config.RedDotsFlagState.None;

    end
    return flag;
end

function RedDotsMailHandler.update()
    RedDotsManager.addBroadcast(Config.RedDotsType.Mail);
end